package com.jinxin.platform.cddjnhjcxtsysset.utils;

import com.jinxin.platform.cddjnhjcxtsysset.common.Constant;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Description: bccah
 * Created by 34759 on 2019/8/16 17:33
 */
@Slf4j
@Component
public class UploadFileUtil {
    private final static Logger logger = LoggerFactory.getLogger(UploadFileUtil.class);

    public static String getFileNameByTime(MultipartFile file){
        DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateStr = format.format(new Date());
        if(file != null){
            String originalName = file.getOriginalFilename();
            String prefix = originalName.substring(originalName.lastIndexOf(".")+1);
            return dateStr + "." + prefix;
        }
        return dateStr;
    }

    public static String uploadFile(MultipartFile file, String uploadPath, String resBasePath){
        try{
            if(file!=null){
                String fileName = file.getOriginalFilename();
                String ext = fileName.substring(fileName.lastIndexOf("."));
                String newfileName = Utils.getUuid() + ext;
                String fileSavePath = Constant.UPLOAD_FILE_MIDDLE_PATH + newfileName;
                String targetPath = uploadPath + fileSavePath;
                File targetFile = new File(targetPath);
                if(!targetFile.getParentFile().exists()){
                    targetFile.getParentFile().mkdirs();
                }
                targetFile.createNewFile();
                file.transferTo(targetFile);
                log.info("上传路径: " + fileSavePath);
                return resBasePath+fileSavePath;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    public static String downFile(String realPath, String fileName , HttpServletResponse response ){
        File file = new File(realPath, fileName);
        logger.info("down file:"+file);
        if (file.exists()) {
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition",
                    "attachment;fileName=" +  fileName);// 设置文件名
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                System.out.println("success");
            } catch (Exception e) {
                logger.error("error",e);
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        logger.error("error",e);
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        logger.error("error",e);
                    }
                }
            }
        }else{
            logger.error( file + "文件不存在");
        }
        return null;
    }

    public static boolean deleteFile(String uploadPath, String filePath){
        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
        String filepath = uploadPath + Constant.UPLOAD_FILE_MIDDLE_PATH + fileName;
        filepath = filepath.replace("\\", "/");
        // 删除附件文件
        File oldPic = new File(filepath);
        if (oldPic.exists()) {
            return oldPic.delete();
        }
        return false;
    }

}
